<template>
  <div class='note-wrapper'>
    <h3 class='tl mb15'>{{ title }}</h3>
    <el-form :model='form' label-width='120px' class='note-form'>
      <el-form-item label='标题:'>
        <el-input v-model='form.title' placeholder='请输入标题'></el-input>
      </el-form-item>
      <el-form-item label='是否可见:'>
        <el-select v-model='form.state' placeholder='请选择是否可见'>
          <el-option label='可见' value='1'></el-option>
          <el-option label='不可见' value='0'></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label='笔记分类:'>
        <el-select v-model='form.type' placeholder='请选择笔记分类'>
          <el-option v-for='option in types' :key='option.value' :label='option.name' :value='option.value'></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label='图标图片'>
        <el-upload ref='fileRefImg' class='upload icons' action='/' :multiple='false' :auto-upload='false' :on-remove='handleRemove' :file-list='fileListImg' :before-upload='beforeUpload'>
          <i class='el-icon-plus avatar-uploader-icon'></i>
          <span class='ml10 file-tip'>请选择图标图片.</span>
        </el-upload>
      </el-form-item>
      <el-form-item label='笔记文档:'>
        <!-- <label>原文件：</label>
        <span class='c6'>{{editItem.filename}}</span>-->
        <el-upload ref='fileRef' class='upload docs' action='/' :multiple='false' :auto-upload='false' :on-remove='handleRemove' :file-list='fileList' :before-upload='beforeUpload'>
          <i class='el-icon-plus avatar-uploader-icon'></i>
          <span class='ml10 file-tip'>请选择10M以内的md、pdf文件.</span>
        </el-upload>
      </el-form-item>
      <el-form-item label='笔记文档图片'>
        <note-images v-on:handleImageChange='handleImageChange' v-bind:images='imageList'></note-images>
      </el-form-item>
      <el-form-item label='笔记描述内容:'>
        <el-input v-model='form.description' :rows='5' type='textarea' placeholder='请输入笔记描述内容'></el-input>
      </el-form-item>
      <el-form-item>
        <p class='btn-area tr'>
          <el-button type='warning' @click='cancel'>取消</el-button>
          <el-button type='primary' @click='submmit'>提交</el-button>
        </p>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { reactive, ref, toRaw, unref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import ptypes from '@/utils/type';
import request from 'request/index';
import { ElNotification } from 'element-plus';
import NoteImages from "./note-images";
import store from "store/index";
export default {
  name: 'note-add',
  setup (props, ctx) {
    const router = useRouter(),
      route = useRoute(),
      user = store.getters['user/userInfo'].name;

    const editItem = route.params;
    const isEdit = route.params && route.params._id;
    const title = ref(isEdit ? '修改笔记' : '新增笔记');

    const types = ref(ptypes);
    const fileListImg = ref([]),
      fileList = ref([]),
      imageList = ref([]);

    const form = reactive({
      title: editItem && editItem.title ? editItem.title : '',
      description: editItem && editItem.description ? editItem.description : '',
      state: editItem && editItem.state ? editItem.state : '',
      type: editItem && editItem.type ? editItem.type : '',
      sfiles: [],
      sfilesIcon: [],
      user: user,
      images: [],
    });

    const handleRemove = () => {
    };
    const beforeUpload = file => {
      // if (fileList.length > 1)      {
      //   return false;
      // }
    };
    const handleImageChange = (images) => {
      imageList.value = images;
    };
    const cancel = () => {
      router.push({ name: 'noteMng' });
    };
    const noteAdd = (sform) => {
      request.postForm('/blog/insert', toRaw(sform)).then(data => {
        if (data.state == 200)        {
          ElNotification({
            message: '笔记添加成功!',
            type: 'success'
          });
          cancel();
        } else        {
          ElNotification({
            message: '笔记添加失败!',
            type: 'error'
          });
        }
      });
    };
    const noteEdit = (sform) => {
      let params = Object.assign({}, toRaw(sform), { _id: editItem._id });

      request.postForm('/blog/update', params).then(data => {
        if (data.state == 200)        {
          ElNotification({
            message: '笔记修改成功!',
            type: 'success'
          });
          cancel();
        } else        {
          ElNotification({
            message: '笔记修改失败!',
            type: 'error'
          });
        }
      });
    };
    const submmit = () => {
      var sform = toRaw(form);
      // 文件
      var input = document.querySelector('.upload.docs .el-upload__input');
      var sfiles = input.files;
      if (!isEdit && (!sfiles || sfiles.length == 0))      {
        return ElNotification({
          message: '请选择文件',
          type: 'warning'
        });
      }
      // 解除响应式
      sform.sfiles = sfiles && sfiles.length > 0 ? [sfiles[0]] : [];

      // icon图片
      input = document.querySelector('.upload.icons .el-upload__input');
      let sfilesIcon = input.files;
      // 解除响应式
      sform.sfilesIcon = sfilesIcon && sfilesIcon.length > 0 ? [sfilesIcon[0]] : [];

      const images = [];
      unref(imageList).forEach(file => {
        if (file && file.raw && file.raw instanceof File)        {
          images.push(file.raw);
        }
      })
      sform.images = images;

      if (!sform.sfiles || sform.sfiles.length == 0)      {
        sform.sfiles == []
      }
      if (!sform.sfilesIcon || sform.sfilesIcon.length == 0)      {
        sform.sfilesIcon == [];
      }
      if (!sform.images || sform.images.length == 0)      {
        sform.images == [];
      }

      isEdit ? noteEdit(sform) : noteAdd(sform);
    };

    onMounted(() => {
      if (isEdit)      {
        const id = editItem._id;
        request.get(`/blog/detail/${id}`).then(resp => {
          if (resp && resp.data)          {
            const sfiles = resp.data.sfiles || [];
            if (sfiles && sfiles.length > 0)            {
              fileList.value = sfiles;
            }
            const images = resp.data.images || [];
            if (images && images.length > 0)            {
              imageList.value = images;
            }
            const sfilesIcon = resp.data.sfilesIcon || [];
            if (sfilesIcon && sfilesIcon.length > 0)            {
              fileListImg.value = sfilesIcon;
            }
          }
        });
      }
    })

    return {
      editItem,
      title,
      types,
      form,
      cancel,
      submmit,
      fileList,
      fileListImg,
      imageList,
      handleImageChange,
      handleRemove,
      beforeUpload
    };
  },
  components: {
    NoteImages
  }
};
</script>

<style lang="scss" scoped>
.note-form {
  width: 550px;
  margin: 0 auto;
}
.note-form .el-form-item__content .el-select {
  width: 100%;
}
::v-deep .note-form .el-upload .file-tip {
  color: #ddd;
}
::v-deep .el-upload:hover .avatar-uploader-icon {
  border-color: #409eff;
}
::v-deep .note-form .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;

  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.c6 {
  color: #666;
}
</style>
